package com.itfreer.setting.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;

import com.itfreer.core.collection.SerializableMap;
import com.itfreer.core.config.ConfigManager;
import com.itfreer.gis.offline.IBaseOffline;
import com.itfreer.gis.config.GisConfigManager;
import com.itfreer.gis.offline.OfflineSynService;
import com.itfreer.gis.ui.activity.LocusEventsActivity;
import com.itfreer.gis.ui.activity.LocusListActivity;
import com.itfreer.gis.ui.activity.OfflineActivity;
import com.itfreer.metadata.version.AppVersion;
import com.itfreer.metadata.version.DataVersionService;
import com.itfreer.setting.R;
import com.itfreer.core.security.SecurityService;
import com.itfreer.core.security.UserInfoEntity;
import com.itfreer.setting.configsyn.ConfigSynUtils;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.ui.base.TextView;
import com.itfreer.utils.AlertUtils;
import com.itfreer.utils.MyProgressDialog;
import com.itfreer.utils.ToastUtils;

import java.io.Serializable;

/**
 * 我的界面
 */
public class SettingActivity extends BaseActivity {

    private TextView userNameText;
    private TextView loginButton;

    private ConfigSynUtils configSynUtils;

    // 数据同步弹窗
    private MyProgressDialog dataSynDialog;
    // 数据同步处理器
    private DataSynHandler dataSynHandler;
    // 待同步数量
    private com.itfreer.ui.base.TextView setting_upload_num;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setNavigationBarColor();

        setContentView(R.layout.activity_setting);

        configSynUtils = new ConfigSynUtils(this);
        dataSynDialog = new MyProgressDialog(this);
        dataSynHandler = new DataSynHandler();

        // 返回
        TextView back =(TextView)findViewById(R.id.setting_back);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });

        // 系统登录
        loginButton = (TextView)findViewById(R.id.setting_login);
        loginButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(loginButton.getText().equals("登录/注册")){
                    goLoginPage();
                }else{
                    logout();
                }
            }
        });

        // 修改密码
        LinearLayout password =(LinearLayout)findViewById(R.id.setting_password);
        password.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(ConfigManager.getUser() == null){
                    ToastUtils.showShort(SettingActivity.this, "请先系统登录！");
                    return;
                }
                goPasswordPage();
            }
        });

        // 关于
        LinearLayout about = findViewById(R.id.setting_about);
        about.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goAboutPage();
            }
        });

        // 权限设置
        LinearLayout power = findViewById(R.id.setting_power);
        power.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goPowerPage();
            }
        });

        // 数据同步
        LinearLayout dataSyn = findViewById(R.id.dataSynLayout);
        dataSyn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dataSyn(true, "数据同步");
            }
        });

        // 数据上传
        setting_upload_num = findViewById(R.id.setting_upload_num);
        Integer uploadNum = OfflineSynService.instance.uploadNumber();
        if(uploadNum == 0){
            setting_upload_num.setText("增量数据上传");
        } else {
            setting_upload_num.setText("有" + uploadNum.toString() + "条数据待上传");
        }
        LinearLayout dataUpdateLayout = findViewById(R.id.dataUpdateLayout);
        dataUpdateLayout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dataSyn(false, "数据上传");
            }
        });

        // 巡护轨迹
        LinearLayout locusActivity = (LinearLayout) findViewById(R.id.locusActivity);
        locusActivity.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goLocus();
            }
        });

        // 巡护事件
        LinearLayout locusEventActivity = (LinearLayout) findViewById(R.id.locusEventActivity);
        locusEventActivity.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goLocusEvent();
            }
        });

        // 底图数据同步
        LinearLayout offline = (LinearLayout) findViewById(R.id.offlineLayout);
        offline.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 打开数据同步窗口
                ToastUtils.showShort(SettingActivity.this, "功能开发中...");
            }
        });

        // APP更新
        LinearLayout appUpdate = (LinearLayout) findViewById(R.id.appUpdate);
        appUpdate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AppVersion.instance.initVariable(SettingActivity.this);
                AppVersion.instance.execute(true);
            }
        });

        // 配置同步
        LinearLayout configSyn = (LinearLayout) findViewById(R.id.configSynLayout);
        configSyn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AlertUtils.dialog(SettingActivity.this, "系统提示", "确认启动配置同步操作？",
                        new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                configSynUtils.configSyn(true, true);
                            }
                        },
                        new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }
                );
            }
        });

        // 用户信息
        userNameText = (TextView) findViewById(R.id.setting_user_name);
    }

    @Override
    protected void onStart() {
        super.onStart();
        setUserInfo(ConfigManager.getUser());
    }

    /**
     * 设置用户信息
     */
    private void setUserInfo(UserInfoEntity user){
        if(user != null){
            userNameText.setText(user.getUserName());
            loginButton.setText("注销登录");
        }else{
            userNameText.setText("未登录");
            loginButton.setText("登录/注册");
        }
    }

    protected void goOfflinePage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, OfflineActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    protected void goLoginPage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, LoginActivity.class);
        // 启动一个新的Activity
        this.startActivityForResult(intent, 1);
    }

    protected void logout() {
        AlertUtils.dialog(this, "系统提示", "切换帐号将切换地图数据，您确认退出吗？",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DataVersionService.instance.delete();
                        SecurityService.instance.logout();
                        setUserInfo(ConfigManager.getUser());

                        ConfigSynUtils configSynUtils = new ConfigSynUtils(SettingActivity.this);
                        configSynUtils.configSyn(false, true);
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which){
                    }
                }
        );
    }

    protected void goAboutPage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, AboutActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    protected void goPowerPage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, PowerActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    protected void goLocusEvent() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, LocusEventsActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // 启动一个新的Activity
        startActivityForResult(intent, 2);
    }

    protected void goLocus() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, LocusListActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // 启动一个新的Activity
        startActivityForResult(intent, 3);
    }

    protected void goPasswordPage() {
        if(ConfigManager.getUser()==null){
            ToastUtils.showShort(SettingActivity.this, "请先登录");
            return;
        }

        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, PasswordActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    protected void dataSyn(final Boolean download, String title) {
        if(ConfigManager.getUser()==null){
            ToastUtils.showShort(SettingActivity.this, "请先登录");
            return;
        }

        AlertUtils.dialog(SettingActivity.this, "系统提示", "确认启动" + title +"吗？",
            new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showDataSynDialog();
                    OfflineSynService.instance.synData(download, new OfflineSynService.ProgressListener(){
                        @Override
                        public void onSize(int count, int size, String s) {
                            Message msg = new Message();
                            Bundle b = new Bundle();
                            b.putString("message", s);
                            b.putInt("progress", size);
                            b.putInt("count", count);
                            b.putBoolean("result", true);
                            b.putBoolean("success", false);
                            msg.setData(b);
                            dataSynHandler.sendMessage(msg);
                        }

                        @Override
                        public void onFail(String info) {
                            Message msg = new Message();
                            Bundle b = new Bundle();
                            b.putString("message", info);
                            b.putInt("progress", 7);
                            b.putInt("count", 7);
                            b.putBoolean("result", false);
                            b.putBoolean("success", false);
                            msg.setData(b);
                            dataSynHandler.sendMessage(msg);
                        }

                        @Override
                        public void onSuccess() {
                            Message msg = new Message();
                            Bundle b = new Bundle();
                            b.putString("message", "同步成功");
                            b.putInt("progress", 6);
                            b.putInt("count", 6);
                            b.putBoolean("result", true);
                            b.putBoolean("success", true);
                            msg.setData(b);
                            dataSynHandler.sendMessage(msg);
                        }
                    });
                }
            },
            new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }
        );
    }

    /**
     * 启动数据同步进度对话框
     */
    private void showDataSynDialog(){
        // 设置对话框参数
        dataSynDialog.setTitle("数据同步");
        dataSynDialog.setMessage("启动数据同步");
        dataSynDialog.setCancelable(false);
        // 设置进度条参数
        dataSynDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dataSynDialog.setMax(9);
        dataSynDialog.setProgress(0);
        dataSynDialog.setIndeterminate(false); // 填false表示是明确显示进度的 填true表示不是明确显示进度的
        dataSynDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(OfflineSynService.instance.getIsRuning()) return;

                // 刷新当前地图
                IBaseOffline offline = GisConfigManager.getOffline();
                offline.refresh();
                dataSynDialog.dismissManually();
            }
        });
        dataSynDialog.show();
    }

    private class DataSynHandler extends Handler {
        public DataSynHandler() {
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 此处可以更新UI
            Bundle b = msg.getData();
            String s = b.getString("message");
            int size = b.getInt("progress");
            int count = b.getInt("count");
            Boolean success = b.getBoolean("success");
            dataSynDialog.setMessage(s);
            dataSynDialog.setProgress(size);
            dataSynDialog.setMax(count);

            // 4.同步成功后，刷新数据源
            if(success) {
                // 刷新数量
                setting_upload_num = findViewById(R.id.setting_upload_num);
                Integer uploadNum = OfflineSynService.instance.uploadNumber();
                if(uploadNum == 0){
                    setting_upload_num.setText("增量数据上传");
                } else {
                    setting_upload_num.setText("有" + uploadNum.toString() + "条数据待上传");
                }

                dataSynDialog.dismissManually();
                GisConfigManager.getFeature().refreshOfflineSource();
            }
        }
    }

    /**
     * 查询回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==1) {
            if(requestCode==1) {
                ConfigSynUtils configSynUtils = new ConfigSynUtils(SettingActivity.this);
                configSynUtils.configSyn(false, true);
            } else if (requestCode==2) {
                // 事件
                Intent intent = new Intent();
                intent.putExtra("source", data.getStringExtra("source"));
                intent.putExtra("datas", (Serializable) data.getSerializableExtra("datas"));
                setResult(RESULT_OK, intent);
                SettingActivity.this.finish();
            } else if (requestCode==3) {
                // 轨迹
                Intent intent = new Intent();
                intent.putExtra("source", data.getStringExtra("source"));
                intent.putExtra("datas", (Serializable) data.getSerializableExtra("datas"));
                setResult(RESULT_OK, intent);
                SettingActivity.this.finish();
            }
        }
    }
}
